package com.itbaizhan.controller;

import com.itbaizhan.domain.User;
import com.itbaizhan.idempotency.ApiIdempotentAnn;
import com.itbaizhan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.UUID;

/**
 * @author spf
 * @date 2024/4/26
 * @time 17:13
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/index")
    public ModelAndView list() {
        List<User> userList = userService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("users", userList);
        return modelAndView;
    }


    @GetMapping("/toAdd")
    public ModelAndView toAdd() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("add");
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(token,Thread.currentThread().getId() + "");
        modelAndView.addObject("token",token);
        return modelAndView;
    }

    @PostMapping("/create")
    @ApiIdempotentAnn
    public String create(@RequestParam("name") String name, @RequestParam("age") Integer age) throws InterruptedException {
        Thread.sleep(3000);
        int insert = userService.insert(name, age);
        if (insert >= 1){
            return "redirect:index";
        }
        return "add";
    }

    @GetMapping("/getUserById")
    public ModelAndView getUserById(@RequestParam("id") Long id){
        User user = userService.findById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("update");
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    @PostMapping("/update")
    public String update(User user) throws InterruptedException {
        Thread.sleep(3000);
        int update = userService.update(user);
        if (update >= 1){
            return "redirect:index";
        }
        return "update";
    }

}
